<template>
  <div class="app-container">
    <Ht-search-form
      :dictMap="dictMap"
      :searchExtend="extendSearch"
      :queryParams="queryParams"
      :outputQueryParams="queryParams"
      :formOptions="formOptions"
      :advOptions="[]"
      permission="user:roleInfo:view"
    ></Ht-search-form>

    <!-- 表格数据 -->
    <ht-table
      ref="dataTable"
      :multi-select="true"
      :dictMap="dictMap"
      :queryParams="queryParams"
      :tableBindColumns="tableBindColumns"
      :extendColumns="extendColumns"
      :reqConfig="regConfig"
      :uploadServiceName="'authorityFileService'"
    >
      <template v-slot:operate>
        <el-table-column
          :label="$t('common.operate')"
          align="center"
          width="130"
          fixed="right"
        >
          <template slot-scope="scope">
            <el-button
              v-if="scope.row.reviewStatus==='0'"
              size="mini"
              type="text"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['user:roleInfo:edit']"
            >审核
            </el-button>

            <el-button
              v-else
              size="mini"
              type="text"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['user:roleInfo:edit']"
            >详情
            </el-button>

          </template>
        </el-table-column>
      </template>
    </ht-table>

    <!-- 添加或修改弹出框 -->
    <el-dialog
      :title="title"
      center
      :visible.sync="open"
      width="1024px"
      append-to-body
      @close="close()"
    >
      <el-form
        ref="addForm"
        :model="addForm"
        label-width="110px"
        :disabled="true"
      >

        <el-card class="form-card txnInfo-card" v-if="['2', '1', '17'].includes(this.addForm.opType)">
          <div slot="header" class="label-header-msg">
            <span>基础数据变化</span>
          </div>
          <el-table
            :data="addForm.compareFields"
            :cell-class-name="tableCellClassName"
            style="width: 100%"
          >
            <el-table-column label="属性名" prop="desc">
            </el-table-column>
            <el-table-column label="修改前" prop="originValue">
              <template slot-scope="scope">
                <div v-if="scope.row.desc==='部门ID'">
                  <ht-dept-select-tree
                    disabled
                    ref="deptTree"
                    key="editUser"
                    v-model="scope.row.originValue"
                    :radio="true"
                    node-key="code"
                    @otherChangeChecked="treeChangeChecked"
                  ></ht-dept-select-tree>
                </div>
                <div v-else>
                  {{scope.row.originValue === '[null]' || scope.row.originValue === '[]' ? '': scope.row.originValue}}
                </div>
              </template>
            </el-table-column>
            <el-table-column label="修改后" prop="newValue">
              <template slot-scope="scope">
                <div v-if="scope.row.desc==='部门ID'">
                  <ht-dept-select-tree
                    disabled
                    ref="deptTree"
                    key="editUser"
                    v-model="scope.row.newValue"
                    :radio="true"
                    node-key="code"
                    @otherChangeChecked="treeChangeChecked"
                  ></ht-dept-select-tree>
                </div>
                <div v-else>
                  {{scope.row.newValue === '[null]' || scope.row.newValue === '[]' ? '': scope.row.newValue}}
                </div>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
        <!--        <el-card class="form-card txnInfo-card">
                  <div slot="header" class="label-header-msg">
                    <span>菜单权限变化</span>
                  </div>
                  <el-row type="flex">
                    <el-col :span="12">
                      <el-form-item
                        :label="$t('authority.roleInfo.form.menuPermission')"
                        prop="menuIds"
                      >
                        <div class="tree-container">
                          <el-tree
                            ref="tree"
                            :data="treeData"
                            :props="defaultProps"
                            node-key="id"
                            :disabled="true"
                            show-checkbox
                            @check-change="handleCheckChange"
                          ></el-tree>
                        </div>
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item
                        :label="$t('authority.roleInfo.form.menuPermission')"
                        prop="menuIds"
                      >
                        <div class="tree-container">
                          <el-tree
                            ref="modifitree"
                            :data="treeData"
                            :props="defaultProps"
                            node-key="id"
                            :disabled="true"
                            :render-content="renderContent"
                            show-checkbox
                            @check-change="handleCheckChange"
                          ></el-tree>
                        </div>
                      </el-form-item>
                    </el-col>
                  </el-row>
                </el-card>-->
        <el-card class="form-card txnInfo-card">
          <div slot="header" class="label-header-msg">
            <span>审核信息</span>
          </div>
<!--          <el-form-item  prop="treeDeptIds" >-->
<!--            <ht-dept-select-tree-->
<!--              ref="deptTree"-->
<!--              key="editUser"-->
<!--              v-model="treeDeptIds"-->
<!--              :radio="true"-->
<!--              node-key="id"-->
<!--              @otherChangeChecked="treeChangeChecked"-->
<!--            ></ht-dept-select-tree>-->
<!--          </el-form-item>-->
          <el-row type="flex">
            <el-col :span="12">
              <el-form-item label="操作类型" prop="opType">
                <el-select style="width: 100%;" v-model="addForm.opType" placeholder="操作类型">
                  <el-option
                    v-for="dict in dictMap.OP_TYPE"
                    :key="dict.value"
                    :label="`${dict.value}-${dict.text}`"
                    :value="dict.value"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row type="flex">
            <el-col :span="12">
              <el-form-item label="操作者" prop="createBy">
                <el-input v-model="addForm.createBy"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="操作时间" prop="mdTime">
                <el-date-picker style="width: 100%;" v-model="addForm.createTime" value-format="yyyyMMddHHmmss"
                                type="datetime"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row type="flex">
            <el-col :span="12">
              <el-form-item label="审核状态" prop="reviewStatus">
                <el-select style="width: 100%;" v-model="addForm.reviewStatus" placeholder="审核状态">
                  <el-option
                    v-for="dict in dictMap.REVIEW_STATUS"
                    :key="dict.value"
                    :label="`${dict.value}-${dict.text}`"
                    :value="dict.value"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row type="flex">
            <el-col :span="12">
              <el-form-item label="审核者" prop="reviewBy">
                <el-input v-model="addForm.reviewBy"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="审核时间" prop="reviewTime">
                <el-date-picker style="width: 100%;" v-model="addForm.reviewTime" value-format="yyyyMMddHHmmss"
                                type="datetime"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-card>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="approve" v-if="this.addForm.reviewStatus==='0'"
                   >审 核
        </el-button>
        <el-button type="danger" @click="reject" v-if="this.addForm.reviewStatus==='0'"
                   >拒 绝
        </el-button>
        <el-button @click="cancel">{{ $t("common.cancel") }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {property} from "@/api/authority_app/base";
import {
  apiUrlConfig,
  approve,
  reject
} from "@/api/authority_app/user/userInfoApprove";
import {listPageMixin} from "@/libs/listPageMixin";
import {mapGetters} from "vuex";
import {stopPayApplyApproveApprove, stopPayApplyApproveReject} from "@/api/cnaps/beps/411";
import {rolesByUserId} from "@/api/authority_app/role/roleInfo";
import {searchPostByStatusVue} from "@/api/authority_app/post/postInfo";

export default {
  name: "userInfoApprove",
  components: {},
  mixins: [listPageMixin],
  data() {
    return {
      treeDeptIds: "",
      entryTable: 'entryTable',
      mutiTeanant: false,
      // 弹出层标题
      title: "",
      //遮罩层
      loading: false,
      // 是否显示弹出层
      searchFormDictList: ['OP_TYPE', 'REVIEW_STATUS'],
      open: false,
      //菜单权限
      treeData: [],
      //级联关系
      defaultProps: {
        label: "name",
        children: "children",
      },
      tenantOptions: [],
      // 表单参数
      addForm: {
        roleName: "",
        roleKey: "",
        status: "1",
        remark: "",
        roleSort: "",
        tenantCode: "",
        menuIds: [],
        expandValueInfoMap: {},
      },

      // 当前勾选菜单ID
      checkedKeys: [],
      // 原勾选菜单ID
      originCheckedKeys: [],

      extendParentKey: "3",

      formOptions: [],
      // 查询参数
      queryParams: {
        current: 1,
        limit: 10,
        roleName: "",
        reviewStatus: "0",
        roleKey: "",
        status: "",
      },
      regConfig: apiUrlConfig,

      isAble: false,
      tenantCodeIsAble: false,
      tableBindDetailColumns: [
        {label: '属性名', prop: 'desc'},
        {label: '修改前', prop: 'originValue'},
        {label: '修改后', prop: 'newValue'},
      ],
      // 列信息
      tableBindColumns: [
        {
          label: this.$t("authority.roleInfo.form.id"),
          prop: "id",
          visible: false,
        },
        {
          label: this.$t("authority.roleInfo.form.tenantCode"),
          prop: "tenantCode",
        },
        {label: '用户名', prop: "userName"},
        {label: '登录名称', prop: "loginName"},
        {label: '操作类型', prop: "opType", dictCode: 'OP_TYPE'},
        {label: '操作者', prop: 'createBy'},
        {label: '操作时间', prop: 'createTime'},
        {label: '审核状态', prop: 'reviewStatus', dictCode: 'REVIEW_STATUS'}


      ],

      searchExtendColumns: [],
      sexOptions: []
    };
  },
  mounted() {
    property().then((res) => {
      this.mutiTeanant = res.result.multipleCorporate;
    });
    const formOptions = [
      {
        type: "input",
        prop: "userName",
        defaultAttr: {
          size: "small",
          label: "用户名",
          placeholder: "用户名",
        },
      },
      {
        type: "dict",
        dict: "REVIEW_STATUS",
        prop: "reviewStatus",
        defaultAttr: {
          size: "small",
          label: '审核状态',
          placeholder: '审核状态',
        },
      },
    ];
    this.formOptions = formOptions;
  },
  created() {
    this.getDicts("sys_user_sex").then((response) => {
      this.sexOptions = response.result;
    });
  },
  methods: {
    treeChangeChecked(res) {
      console.log('treeChangeChecked')
    },
    getDictReq(dictCode) {
      return this.getDicts(dictCode);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.$set(this, "addForm", {
        roleName: "",
        roleKey: "",
        status: "1",
        remark: "",
        roleSort: "",
        menuIds: [],
        expandValueInfoMap: {},
      });
      // this.resetForm("addForm");
      // this.$refs.htExtendForm.clearInput();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    refreshTreeData(tenantCode) {
      this.allMenuTreeNew(tenantCode);
    },

    /** 审核详情按钮操作 */
    handleUpdate: function (row) {
      var map = new Map();
      this.resetForm("addForm");
      this.checkedReset();
      this.title = "用户审核";
      this.addForm.id = row.id;
      this.addForm.tenantCode = row.tenantCode
      this.addForm.reviewId = row.reviewId
      // 新增或修改 委任用户
      if (['1', '2', '17'].includes(row.opType)) {
        this.addForm.compareFields = row.reviewCompareInfo === undefined ? '' : JSON.parse(row.reviewCompareInfo);
        this.addForm.compareFields.forEach(compareField => {
          map.set(compareField.name, compareField);
        })
        this.treeDeptIds = '1111';
        this.addForm.expandValueInfoMap = row.expandValueInfoMap || {};
      /*  rolesByUserId(null, null, row.tenantCode).then((res) => {
          const roleOptions = res.result;
          const newStr = map.get("roleIds").newValue;
          const orgStr = map.get("roleIds").originValue;
          const roleMap = new Map(roleOptions.map(role => [role.id, role.roleName]));
          const newRoleIds = newStr.substring(1, newStr.length - 1).split(", ");
          const newRoleNames = newRoleIds.map(id => roleMap.get(id)).join("，");
          const orgRoleIds = orgStr.substring(1, orgStr.length - 1).split(", ");
          const orgRoleNames = orgRoleIds.map(id => roleMap.get(id)).join("，");
          map.get("roleIds").newValue = newRoleNames;
          map.get("roleIds").originValue = orgRoleNames;
        });
        if (map.get("postIds")) {
          searchPostByStatusVue().then((res) => {
            if (res && res.result && res.result.length > 0) {
              const postOptions = res.result;
              const newStr = map.get("postIds").newValue;
              const orgStr = map.get("postIds").originValue;
              const postMap = new Map(postOptions.map(post => [post.id, post.postName]));
              const newRoleIds = newStr.substring(1, newStr.length - 1);
              const orgRoleIds = orgStr.substring(1, orgStr.length - 1);
              map.get("postIds").newValue = postMap.get(newRoleIds);
              map.get("postIds").originValue = postMap.get(orgRoleIds);
            }
          })
        }*/
        if (map.get("sex")) {
          console.log("this.sexOptions",this.sexOptions)
          this.sexOptions.forEach(sex => {
            if (sex.value === map.get("sex").originValue) {
              map.get("sex").originValue = sex.text;
            }
            if (sex.value === map.get("sex").newValue) {
              map.get("sex").newValue = sex.text;
            }
          })
        }
        if (map.get("status")) {
          var statusMap = new Map();
          statusMap.set("1", "正常");
          statusMap.set("2", "禁用/锁定");
          map.get("status").originValue = statusMap.get(map.get("status").originValue);
          map.get("status").newValue = statusMap.get(map.get("status").newValue);
        }
      }
      this.addForm.opType = row.opType;
      this.addForm.createBy = row.createBy;
      this.addForm.createTime = row.createTime;
      this.addForm.reviewStatus = row.reviewStatus;
      this.addForm.reviewBy = row.reviewBy;
      this.addForm.reviewTime = row.reviewTime;
      this.open = true;

      // checkRoleUpdatePermission(row.tenantCode).then((response) => {
      //   this.isAble = !response.result;
      //   this.tenantCodeIsAble = !response.result;
      // });

      // allMenuTreeNew(row.tenantCode).then((response) => {
      //   this.treeData = response.result;
      //
      //   this.queryRoleMenuList();
      //   this.$nextTick((res) => {
      //     this.originCheckedKeys = JSON.parse(row.originMenus)
      //     this.queryRoleMenuList1(this.originCheckedKeys);
      //   });
      // });
    },

    //查询角色菜单权限
    allMenuTreeNew(tenantCode) {
      allMenuTreeNew(tenantCode).then((response) => {
        this.treeData = response.result;
      });
    },

    getMyTenants() {
      getMyTenants().then((response) => {
        this.tenantOptions = response.result;
        if (this.tenantOptions.length == 1) {
          this.addForm.tenantCode = this.tenantOptions[0].tenantCode;
          this.tenantCodeIsAble = true;
        }
      });
    },

    //查询角色菜单权限
    queryRoleMenuList() {
      listRoleMenuTmpList({reviewId: this.addForm.reviewId}).then((response) => {
        this.checkedKeys = response.result;
        response.result.forEach((id) => {
          this.$refs.modifitree.setChecked(id, true);
        });
      });
    },

    //查询角色菜单权限
    queryRoleMenuList1(originMenus) {
      originMenus.forEach((id) => {
        this.$refs.tree.setChecked(id, true);
      });
    },
    //选中变更
    //属性组件选择后的回调
    handleCheckChange() {
      let temp = this.$refs.tree.getCheckedKeys();
      var ids = temp.concat(this.$refs.tree.getHalfCheckedKeys());
      this.addForm.menuIds = ids;
    },

    //选中重置
    checkedReset() {
      if (this.$refs.tree) {
        var ids = this.$refs.tree
          .getCheckedKeys()
          .concat(this.$refs.tree.getHalfCheckedKeys());
        if (ids.length > 0) {
          this.$refs.tree.setCheckedKeys([]);
        }
      }
    },
    changeShowExtendSearch(state) {
      this.$refs.htExtendSearch.changeShowState(state);
    },
    // 取消按钮
    close() {
      this.open = false;
    },


    renderContent(h, {node, data, store}) {
      if (this.nodeChanged(node)) {
        return <span style="color:red">{node.label}</span>;
      } else {
        return <span>{node.label}</span>;
      }
    },
    nodeChanged(node) {
      let current = this.checkedKeys.indexOf(node.data.id) > -1;
      let origin = this.originCheckedKeys.indexOf(node.data.id) > -1;
      let changed = origin != current;

      if (!changed) {
        let childs = node.childNodes;
        if (childs) {
          for (let i = 0, len = childs.length; i < len; i++) {
            let child = childs[i];
            if (this.nodeChanged(child)) {
              return true;
            }
          }
        }
      }

      return changed;
    },
    tableCellClassName({row, column, rowIndex, columnIndex}) {
      if (columnIndex > 0 && row.changeFlag == "1") {
        return "warning-cell";
      } else {
        return "";
      }
    },
    //审核通过按钮
    approve() {
      this.$refs["addForm"].validate((valid) => {
        if (valid) {
          this.loading = true;
          approve(this.addForm)
            .then((response) => {
              this.msgSuccess("审核通过");
              this.open = false;
              this.loading = false;
              this.$nextTick(() => {
                this.$refs.dataTable.doQuery(true);
              });
            })
            .catch((err) => {
              this.loading = false;
            });
        }
      });
    },
    //审核拒绝按钮
    reject() {
      this.$refs["addForm"].validate((valid) => {
        if (valid) {
          this.loading = true;
          reject(this.addForm)
            .then((response) => {
              this.msgSuccess("审核拒绝");
              this.open = false;
              this.loading = false;
              this.$nextTick(() => {
                this.$refs.dataTable.doQuery(true);
              });
            })
            .catch((err) => {
              this.loading = false;
            });
        }
      });
    },
  },
};
</script>
<style>
.tree-container {
  max-height: 350px;
  overflow: auto;
}

.el-table .warning-cell {
  color: red;
}

.label-header-msg {
  font-weight: bold;
}

.form-card {
  margin-bottom: 10px;
}
</style>
